package reaction

import (
	"context"
	"strconv"
	"time"

	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/blog/model"
	"mall/service/blog/rpc/internal/svc"
	"mall/service/blog/rpc/internal/utils/errorhandler"
	"mall/service/blog/rpc/types/blog"

	"github.com/zeromicro/go-zero/core/logx"
)

type LogReactionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLogReactionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LogReactionLogic {
	return &LogReactionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LogReactionLogic) LogReaction(in *blog.LogReactionReq) (*blog.BaseIDResp, error) {
	if in.PostId == 0 || in.PostType == 0 {
		return nil, resultx.NewErrCode(resultx.FORUM_REACTION_CONTENT_ID_INVALID)
	}

	if in.UserId == 0 {
		return nil, resultx.StatusError(resultx.FORUM_REACTION_USER_ID_INVALID, "")
	}

	if len(in.Type) == 0 {
		return nil, resultx.StatusError(resultx.FORUM_REACTION_TYPE_INVALID, "")
	}

	var count uint64
	var log *model.BlogReactionLog
	subFilterMap := make(map[string]map[string][]any)
	subFilterMap[model.BlogReactionLogColumns.UserID] = map[string][]any{
		"equalTo": {in.UserId},
	}
	subFilterMap[model.BlogReactionLogColumns.PostID] = map[string][]any{
		"equalTo": {in.PostId},
	}
	subFilterMap[model.BlogReactionLogColumns.PostType] = map[string][]any{
		"equalTo": {in.PostType},
	}
	subFilterMap[model.BlogReactionLogColumns.Type] = map[string][]any{
		"equalTo": {in.Type},
	}
	userLogs, _, err := l.svcCtx.Reaction.GetList(l.ctx, model.M{
		"pageSize": uint64(1),
		"orderBy":  model.BlogReactionLogColumns.ID + " DESC",
	}, -1, subFilterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(userLogs) > 0 {
		log = userLogs[0]
		if uint8(in.Status) == log.Status { // 状态未变，即接口被重复调用
			return &blog.BaseIDResp{
				Id: log.ID,
			}, nil
		}
	} else if int32(in.Status) == globalkey.StatusDisabled { // 原来无记录，首次操作即取消，忽略
		return &blog.BaseIDResp{}, nil
	}

	filterMap := make(map[string]map[string][]any)
	filterMap[model.BlogReactionLogColumns.PostID] = map[string][]any{
		"equalTo": {in.PostId},
	}
	filterMap[model.BlogReactionLogColumns.PostType] = map[string][]any{
		"equalTo": {in.PostType},
	}
	filterMap[model.BlogReactionLogColumns.Type] = map[string][]any{
		"equalTo": {in.Type},
	}
	logs, _, err := l.svcCtx.Reaction.GetList(l.ctx, model.M{
		"pageSize": uint64(1),
		"orderBy":  model.BlogReactionLogColumns.ID + " DESC",
	}, -1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(logs) > 0 {
		count = logs[0].Count
	}

	now := time.Now()
	date := now.Format("20060102")
	var createDate int
	if i, err := strconv.ParseInt(date, 10, 64); err == nil {
		createDate = int(i)
	}
	newLog := &model.BlogReactionLog{
		PostID:     in.PostId,
		PostType:   uint8(in.PostType),
		UserID:     in.UserId,
		Type:       in.Type,
		Status:     uint8(in.Status),
		CreatedAt:  now,
		CreateDate: createDate,
	}

	if int32(in.Status) == globalkey.StatusEnabled { // 操作
		count += 1
	} else if count > 0 && int32(in.Status) == globalkey.StatusDisabled { // 取消操作
		count -= 1
	}

	newLog.Count = count
	err = l.svcCtx.Reaction.Insert(l.ctx, nil, newLog)
	if err != nil {
		return nil, err
	}

	return &blog.BaseIDResp{
		Id: newLog.ID,
	}, nil
}
